package icu.javayanglei.bilibili.community.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.javayanglei.bilibili.community.service.DmService;
import icu.javayanglei.bilibili.community.service.dm.v1.DanmakuElem;
import icu.javayanglei.bilibili.community.service.dm.v1.DmSegMobileReply;
import icu.javayanglei.bilibili.domain.Dm;
import icu.javayanglei.bilibili.domain.vo.QueryDM;
import icu.javayanglei.bilibili.mapper.DmMapper;
import icu.javayanglei.bilibili.util.MyFileUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

/**
 * dm 实现类
 *
 * @author yang
 */
@Service
public class DmServiceImpl extends ServiceImpl<DmMapper, Dm> implements DmService {

    @SneakyThrows
    @Override
    public List<Dm> getDm(QueryDM query) {
        List<Dm> result = CollUtil.newArrayList();
        final HttpRequest request = HttpRequest.get("https://api.bilibili.com/x/v2/dm/web/history/seg.so").form(BeanUtil.beanToMap(query)).cookie("SESSDATA=26d97fcf%2C1656854927%2Cf3a04*11;");
        final HttpResponse response = request.executeAsync();
        final File temp = MyFileUtil.createTemp();
        response.writeBody(temp);
        final DmSegMobileReply from = DmSegMobileReply.parseFrom(FileUtil.readBytes(temp));
        final List<DanmakuElem> elemsList = from.getElemsList();
        if (CollUtil.isNotEmpty(elemsList)) {
            result = elemsList.stream()
                    .filter(ObjectUtil::isNotNull)
                    .map(this::toDm)
                    .collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public void saveDm(Dm record) {
        final Dm selectOne = this.baseMapper.selectOne(new LambdaQueryWrapper<Dm>().eq(Dm::getDmId, record.getDmId()));
        // 先查询，如果不存在，再插入
        if (ObjectUtil.isNull(selectOne)) {
            this.save(record);
        }
    }

    @Override
    public void saveDm(List<Dm> record) {
        record.forEach(this::saveDm);
    }

    private Dm toDm(DanmakuElem danmakuElem) {
        // 时间戳格式化用
        long thousand = 1000L;
        long mul = Convert.toLong(NumberUtil.mul(danmakuElem.getCtime(), thousand));
        return Dm.builder()
                .content(danmakuElem.getContent())
                .cTime(LocalDateTimeUtil.of(mul))
                .dmId(danmakuElem.getId())
                .midhash(danmakuElem.getMidHash())
                .build();
    }
}




